package test.file;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value="file")
public class FileController {
	
	@RequestMapping(method=RequestMethod.GET, value="index")
	public ModelAndView userManagerPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/one");
		
		System.out.println(111);
		return mv;
	}

	@RequestMapping(value="/upload", method=RequestMethod.POST)
	public ModelAndView userManagerPage(@RequestParam("myFile")MultipartFile file, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/one");
		
		try {
			System.out.println("文件长度:" + file.getSize());
			System.out.println("文件类型:" + file.getContentType());
			System.out.println("文件名称:" + file.getName());
			System.out.println("文件原名:" + file.getOriginalFilename());
			
			String realPath = request.getSession().getServletContext().getRealPath("/image");
			String name = String.valueOf(new Date().getTime()) + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, name));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mv;
	}
}
